//
//  EasouManager.m
//  Archive
//
//  Created by MyMac on 15/8/24.
//  Copyright (c) 2015年 MyMac. All rights reserved.
//

#import "EasouManager.h"

@interface EasouManager()<NSURLConnectionDataDelegate,NSURLConnectionDelegate>

@property(nonatomic,copy)SucceedBlcok succeedBlock;

@property(nonatomic,copy)FailedBlock failedBlock;

@property(nonatomic,strong)NSMutableData *receiveData;

@property(nonatomic,strong)NSURLConnection *connection;

@end


@implementation EasouManager

- (void)dealloc
{
    
    _receiveData = nil; _connection = nil;
    
    _succeedBlock = nil; _failedBlock = nil;
    
    
    NSLog(@"%@--------dealloc",NSStringFromClass([self class]));

    
}

+(instancetype)manager{
    
    
  return [[self alloc] init];
    
}

- (void)Get:(NSString *)str andWithSucceedBlock:(SucceedBlcok)succeedBlock failedBlock:(FailedBlock)failedBlock{
    
    
    _succeedBlock = succeedBlock;
    
    _failedBlock = failedBlock;
    
    
    NSURL *url = [NSURL URLWithString:str];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:25.0f];
    
    _connection = [NSURLConnection connectionWithRequest:request delegate:self];
    
    
}


- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    _receiveData = [[NSMutableData alloc] init];

    
    [_receiveData setLength:0];
}


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    
    [_receiveData appendData:data];
    
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    
    _connection = nil;
    
    if(_failedBlock){
        
        
        _failedBlock(error);
        
    }
    
    
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    
    
    _connection = nil;
    
    if(_succeedBlock){
        
        _succeedBlock(_receiveData);
        
    }
    
    
    
}


- (BOOL)isLoding{
    
    return _connection?YES:NO;
    
    
}
- (void)cancle{
    
    
    [_connection cancel];
    
    _connection = nil;
    
    
}



@end
